#!/usr/bin/env python3
# coding:utf-8

import paho.mqtt.client as mqtt
import time

# MQTT Broker地址和端口
MQTT_BROKER = 'localhost'
MQTT_PORT = 1883

# 请求主题和响应主题
REQUEST_TOPIC = 'request/topic'
RESPONSE_TOPIC = 'response/topic'

# 创建MQTT客户端实例
client = mqtt.Client()

# 定义消息回调函数
def on_message(client, userdata, message):
    print(f"Received response: '{str(message.payload.decode('utf-8'))}' on topic '{message.topic}'")
    # client.disconnect()

# 设置消息回调函数
client.on_message = on_message

# 连接到MQTT Broker
client.connect(MQTT_BROKER, MQTT_PORT, 60)

# 订阅响应主题
client.subscribe(RESPONSE_TOPIC)

# 循环保持客户端运行
client.loop_start()

try:
    while True:
        # 发送请求消息
        request_message = "Hello, this is a request"
        client.publish(REQUEST_TOPIC, request_message)
        print(f"Sent request: '{request_message}' to topic '{REQUEST_TOPIC}'")
        
        # 等待响应
        time.sleep(1)  # 等待1秒以确保消息被处理
except KeyboardInterrupt:
    print("Exiting...")

# 停止循环并断开连接
client.loop_stop()
client.disconnect()
